﻿using Furion.FriendlyException;
using System.Threading;

namespace Photo.Core.Utils
{
    /// <summary>
    /// mutex公共方法
    /// </summary>
    public static class MutexUtil
    {
        /// <summary>
        /// mutex互斥锁
        /// 根据mutKey进行全局互斥，无等待，发现互斥直接报异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mutKey"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static T MutexNoWait<T>(string mutKey, Func<T> action)
        {
            bool isWait = false;
            using (Mutex mut = new Mutex(false, mutKey))
            {
                try
                {
                    isWait = mut.WaitOne(0);
                    if (!isWait)
                    {
                        throw Oops.Oh("当前接口存在正在进行中的访问");
                    }

                    return action();
                }
                finally
                {
                    if (isWait)//WaitOne和ReleaseMutex成对出现
                    {
                        mut.ReleaseMutex();
                    }
                }
            }
        }

        /// <summary>
        /// mutex互斥锁
        /// 根据mutKey进行全局互斥，无等待，发现互斥直接报异常
        /// </summary>
        /// <param name="mutKey"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static void MutexNoWait(string mutKey, Action action)
        {
            bool isWait = false;
            using (Mutex mut = new Mutex(false, mutKey))
            {
                try
                {
                    isWait = mut.WaitOne(0);
                    if (!isWait)
                    {
                        throw Oops.Oh("当前接口存在正在进行中的访问");
                    }

                    action();
                }
                finally
                {
                    if (isWait)//WaitOne和ReleaseMutex成对出现
                    {
                        mut.ReleaseMutex();
                    }
                }
            }
        }



    }
}
